const axios = require('axios');
const logger = require('../config/logger');
const { PrismaClient } = require('@prisma/client');

class SmsService {
  constructor() {
    this.apiUrl = process.env.SMS_API_URL || '';
    this.token = process.env.SMS_API_TOKEN || '';
    this.from = process.env.SMS_FROM_NUMBER || '';
    this.minInterval = 60 * 1000; // 最小发送间隔（60秒）
    this.prisma = new PrismaClient();
  }

  // 检查是否可以发送验证码
  async canSendVerificationCode(phoneNumber) {
    const lastCode = await this.prisma.verificationCode.findFirst({
      where: { phoneNumber },
      orderBy: { createdAt: 'desc' }
    });

    if (!lastCode) return true;
    
    const now = Date.now();
    return now - lastCode.createdAt.getTime() >= this.minInterval;
  }

  // 生成6位数字验证码
  generateVerificationCode() {
    return Math.floor(100000 + Math.random() * 900000).toString();
  }

  // 发送验证码
  async sendVerificationCode(phoneNumber) {
    try {
      // 检查发送频率
      if (!(await this.canSendVerificationCode(phoneNumber))) {
        throw new Error('发送太频繁，请稍后再试');
      }

      const code = this.generateVerificationCode();
      logger.info('发送验证码', { code });
      const response = await axios.post(this.apiUrl, {
        sms_to: phoneNumber,
        sms_from: this.from,
        sms: `Your verification code is: ${code}, valid for 5 minutes.`
      }, {
        headers: {
          'Authorization': `Bearer ${this.token}`
        }
      });
      logger.info('发送验证码', { response });

      if (response.status === 200) {
        // 存储验证码到数据库
        await this.prisma.verificationCode.create({
          data: {
            phoneNumber,
            code,
            expiresAt: new Date(Date.now() + 5 * 60 * 1000)
          }
        });
        return true;
      }
      return false;
    } catch (error) {
      console.error('发送验证码失败:', error);
      throw error;
    }
  }

  // 验证验证码
  async verifyCode(phoneNumber, code) {
    const storedCode = await this.prisma.verificationCode.findFirst({
      where: { 
        phoneNumber,
        code,
        expiresAt: { gt: new Date() }
      },
      orderBy: { createdAt: 'desc' }
    });

    if (!storedCode) {
      return false;
    }

    // 验证成功后删除验证码
    await this.prisma.verificationCode.delete({
      where: { id: storedCode.id }
    });

    return true;
  }
}

module.exports = new SmsService();